<template>
  <div class="charge-container p-4">
    <!-- 1. 查询区 -->
    <el-form inline class="mb-6">
      <el-form-item label="病历号">
        <el-input
            v-model="medicalId"
            placeholder="请输入病历号"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 2. 患者信息 -->
    <el-card class="mb-6">
      <el-form label-width="80px" inline>
        <el-form-item label="姓名">
          <el-input v-model="patient.realname" disabled />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="patient.idnumber" disabled />
        </el-form-item>
        <el-form-item label="家庭住址">
          <el-input v-model="patient.address" disabled />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 3. 消费记录表 -->
    <el-table
        :data="items"
        stripe
        border
        @selection-change="onSelectionChange"
        empty-text="暂无消费记录"
    >
      <!-- 只允许选中 state=2（已开立）的行 -->
      <el-table-column
          type="selection"
          width="55"
          :selectable="isSelectable"
      />

      <el-table-column prop="medicalid" label="病历号" width="100" />
      <el-table-column label="姓名" width="100">
        <template #default>
          {{ patient.realname }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="项目名称" />
      <el-table-column prop="price" label="单价" width="100">
        <template #default="{ row }">
          ￥{{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="num" label="数量" width="80" />
      <el-table-column prop="creationtime" label="开立时间" width="180" />

      <!-- 三态状态映射 -->
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          {{ formatState(row) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 4. 合计 & 收费按钮 -->
    <div class="mt-4 text-right">
      <!-- 收费方式下拉 -->
      <el-select
          v-model="payType"
          placeholder="请选择收费方式"
          style="width:160px; margin-right:16px"
      >
        <el-option
            v-for="ft in feeTypes"
            :key="ft.id"
            :label="ft.name"
            :value="ft.id"
        />
      </el-select>

      <span class="mr-6">
        合计：<strong>￥{{ totalAmount.toFixed(2) }}</strong>
      </span>
      <el-button type="primary" @click="onSettle">
        收费结算
      </el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Charge',
  beforeCreate() {
    this.counter = useCounterStore()
  },
  data() {
    return {
      medicalId: '',
      payType: null,
      feeTypes: [],      // 收费方式列表
      patient: { realname: '', idnumber: '', address: '' },
      items: [],
      selectedItems: []
    }
  },
  computed: {
    // 实时计算已选项目的合计金额
    totalAmount() {
      return this.selectedItems.reduce(
          (sum, item) => sum + item.price * item.num,
          0
      )
    }
  },
  mounted() {
    this.loadFeeTypes()
  },
  methods: {
    // 加载收费方式
    async loadFeeTypes() {
      try {
        const { data } = await axios.get('/api/charge/feetype')
        this.feeTypes = data
      } catch (e) {
        console.error('加载收费方式失败', e)
        ElMessage.error('加载收费方式失败：' + (e.response?.data || e.message))
      }
    },
    // 只允许 state===2 的行可选
    isSelectable(row) {
      return row != null && row.state === 2
    },
    // 安全地把 row.state 转成文字
    formatState(row) {
      if (!row || row.state == null) return ''
      switch (row.state) {
        case 2: return '已开立'
        case 3: return '已作废'
        case 4: return '已收费'
        default: return '未知'
      }
    },
    // 查询
    async onSearch() {
      if (!this.medicalId) {
        ElMessage.warning('请输入病历号')
        return
      }
      try {
        const { data } = await axios.get('/api/charge/items', {
          params: { medicalId: this.medicalId }
        })
        this.patient.realname = data.patient.realname || ''
        this.patient.idnumber = data.patient.idnumber || ''
        this.patient.address  = data.patient.address  || ''
        this.items            = data.items || []
        this.selectedItems    = []
      } catch (error) {
        console.error('查询失败：', error)
        ElMessage.error('查询失败：' + (error.response?.data || error.message))
      }
    },
    // 选中行变化
    onSelectionChange(val) {
      this.selectedItems = val
    },
    // 收费结算（先弹确认框）
    async onSettle() {
      if (!this.payType) {
        ElMessage.warning('请选择收费方式')
        return
      }
      if (!this.selectedItems.length) {
        ElMessage.warning('请先选择要结算的项目')
        return
      }

      // 弹出确认对话框
      try {
        await ElMessageBox.confirm(
            '确认要对选中的项目进行收费结算吗？',
            '收费确认',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )
      } catch {
        // 用户取消，直接返回
        return
      }

      // 用户确认后再执行收费请求
      try {
        const itemIds    = this.selectedItems.map(x => x.id)
        const total      = this.totalAmount
        const operatorId = this.counter.userId

        await axios.post('/api/charge/pay', {
          itemIds,
          payType:    this.payType,
          paid:       total,
          total:      total,
          operatorId
        })
        ElMessage.success('收费成功')
        this.onSearch()
      } catch (error) {
        console.error('收费失败：', error)
        ElMessage.error('收费失败：' + (error.response?.data || error.message))
      }
    }
  }
}
</script>

<style scoped>
.charge-container { padding: 20px; }
.mb-6 { margin-bottom: 24px; }
.mt-4 { margin-top: 16px; }
.mr-6 { margin-right: 24px; }
</style>
